#define  _CRT_SECURE_NO_WARNINGS 1
#include "DoubleList.h"

ListNode* ListCreate(ListDateType x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}

	newnode->val = x;
	newnode->next = NULL;
	newnode->prev = NULL;

	return newnode;
}

ListNode* ListInit()
{
	ListNode* phead = ListCreate(0);
	phead->next = phead;
	phead->prev = phead;

	return phead;
}

void ListPrint(ListNode* phead)
{
	assert(phead);

	printf("phead<->");
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		printf("%d<->", cur->val);
		cur = cur->next;
	}
	printf("\n");
}

void ListPushBack(ListNode* phead,ListDateType x)
{
	assert(phead);
	//ListNode* tail = phead->prev;
	//ListNode* newnode = ListCreate(x);

	//tail->next = newnode;
	//newnode->prev = tail;

	//newnode->next = phead;
	//phead->prev = newnode;

	ListInsert(phead, x);

}

void ListPushFront(ListNode* phead, ListDateType x)
{
	assert(phead);
	//ListNode* newnode = ListCreate(x);
	//ListNode* first = phead->next;

	//phead->next = newnode;
	//newnode->prev = phead;

	//newnode->next = first;
	//first->prev = newnode;
	
	ListInsert(phead->next, x);
}

void ListPopBack(ListNode* phead)
{
	assert(phead);
	assert(phead->next != phead);

	//ListNode* tail = phead->prev;
	//ListNode* tailprev = phead->prev->prev;
	//tailprev->next = phead;
	//phead->prev = tailprev;

	//free(tail);
	
	ListErase(phead->prev);
}

void ListPopFront(ListNode* phead)
{
	assert(phead);
	assert(phead != phead->next);

	//ListNode* first = phead->next;
	//ListNode* second = first->next;

	//phead->next = second;
	//second->prev = phead;

	//free(first);

	ListErase(phead->next);
}

int ListSize(ListNode* phead)
{
	assert(phead);

	int size = 0;
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		++size;
		cur = cur->next;
	}

	return size;
}

void ListInsert(ListNode* pos, ListDateType x)
{
	assert(pos);

	ListNode* posprev = pos->prev;
	ListNode* newnode = ListCreate(x);

	posprev->next = newnode;
	newnode->prev = posprev;

	newnode->next = pos;
	pos->prev = newnode;
}

void ListErase(ListNode* pos)
{
	assert(pos);
	ListNode* posprev = pos->prev;
	ListNode* posnext = pos->next;

	posprev->next = posnext;
	posnext->prev = posprev;
	
	free(pos);
}

void ListDestroy(ListNode* phead)
{
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		ListNode* next = cur->next;
		
		free(cur);
		cur = next;
	}
}